import 'dart:io';

import 'package:enya_app_upgrade/app_info.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:enya_app_upgrade/enya_app_upgrade.dart';
import 'package:get/get.dart';
import 'package:enya_app_upgrade/app_upgrade_style.dart';
// import 'package:dio/dio.dart';

void main() {
  runApp(const GetMaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _enyaAppUpgradePlugin = EnyaAppUpgrade();
  AppInfo? _appInfo;
  double? _downloadProgress;

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    AppInfo? appInfo;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      appInfo = await _enyaAppUpgradePlugin.getAppInfo();
      print("appInfo: ${_appInfo?.packageName}");
      print("appInfo: ${_appInfo?.versionName}");
      print("appInfo: ${_appInfo?.versionCode}");
    } on PlatformException {}

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _appInfo = appInfo;
    });
  }

  // 简化下载方法，直接返回进度
  Future<void> _downloadApp(String url, Function(double) onProgress) async {
    try {
      // 注释掉实际的下载逻辑
      // final dio = Dio();
      // final savePath = await _enyaAppUpgradePlugin.getApkDownloadPath();
      //
      // await dio.download(
      //   url,
      //   savePath,
      //   onReceiveProgress: (received, total) {
      //     if (total != -1) {
      //       onProgress(received / total);
      //     }
      //   },
      // );

      // 模拟下载进度
      for (var i = 0; i <= 100; i++) {
        await Future.delayed(const Duration(milliseconds: 100));
        onProgress(i / 100);
      }
    } catch (e) {
      print('Download error: $e');
      rethrow;
    }
  }

  void _showUpdateDialog({bool forceUpdate = false}) {
    final confirmText = Platform.isIOS ? '前往更新' : '立即更新';

    Get.dialog(
      _enyaAppUpgradePlugin.createDialog(
        "发现新版本",
        "1. 优化用户体验1. 优化用户体验",
        "暂不更新",
        confirmText,
        () {
          if (!forceUpdate) {
            Get.back();
          }
        },
        (updateProgress) async {
          try {
            await _downloadApp(
              'your_download_url',
              updateProgress,
            );
          } catch (e) {
            print('Error during download: $e');
            if (!forceUpdate) {
              Get.back();
            }
          }
        },
        style: AppUpgradeStyle(
          backgroundColor: const Color(0xff222220),
          margin: const EdgeInsets.symmetric(horizontal: 20), // 设置水平边距来控制宽度
          maxHeight: 240,
          titleStyle: const TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
          contentStyle: const TextStyle(
            color: Colors.white,
            fontSize: 14,
          ),
          cancelTextStyle: const TextStyle(
            color: Colors.white,
            fontSize: 14,
            fontWeight: FontWeight.normal,
          ),
          confirmTextStyle: const TextStyle(
            color: Color(0xFF0257F6),
            fontSize: 14,
            fontWeight: FontWeight.bold,
          ),
          buttonHeight: 48,
          dividerColor: Colors.grey.shade800,
          borderRadius: 20,
          progressBarColor: const Color(0xFF0257F6).withOpacity(.8),
          progressBarBackgroundColor: const Color(0xFF0257F6).withOpacity(.2),
          progressTextStyle: const TextStyle(
            color: Colors.white,
            fontSize: 12,
          ),
        ),
        appStoreId: 'your_app_store_id',
        forceUpdate: forceUpdate,
      ),
      barrierDismissible: !forceUpdate,
    );
  }

  // 添加测试按钮的点击处理
  void _testUpdate() {
    _showUpdateDialog(forceUpdate: false); // 测试普通更新
  }

  void _testForceUpdate() {
    _showUpdateDialog(forceUpdate: true); // 测试强制更新
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('Running on: ${_appInfo?.packageName}\n'),
              InkWell(
                onTap: () {},
                child: Text('ios toAppStore'),
              ),
              InkWell(
                onTap: () {
                  _testForceUpdate();
                },
                child: Container(
                  color: Colors.blue,
                  width: 100,
                  height: 50,
                  alignment: Alignment.center,
                  child: const Text(
                    "检查更新",
                    style: TextStyle(color: Colors.white),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
